﻿@using System.Threading

@if ((Tabs != null && Tabs.Any()) || SearchBarVisible)
{
    <ul class="nav nav-tabs @((Tabs == null || !Tabs.Any()) ? "nav-tabs-collapse" : "")">
        @if (Tabs != null && Tabs.Any())
        {
            @foreach (var tab in Tabs)
            {
                <li class="nav-item">
                    <a class="nav-link @((tab.Id == activeTab) ? "active" : "")" @onclick="@(args => Tab(tab.Id))" href="javascript:;">@tab.Label</a>
                </li>
            }
        }

        @if (SearchBarVisible)
        {
            <li class="nav-item search">
                <div class="input-group">
                    <input type="search"
                           placeholder="Search.."
                           class="form-control"
                           value="@searchTerm"
                           @onchange="(args) => Search((string)args.Value)" />
                    <div class="input-group-append">
                        <button class="btn" 
                                @onclick="(args) => { searchTerm = string.Empty; Search(string.Empty); }">
                            <i class="icon ion-md-close"></i>
                        </button>
                    </div>
                </div>
            </li>
        }
    </ul>
}

@code {
    int? activeTab = null;
    string? searchTerm = null;
    CancellationTokenSource cts = new CancellationTokenSource();

    [Parameter] public IEnumerable<TabUI>? Tabs { get; set; }
    [Parameter] public bool SearchBarVisible { get; set; }
    [Parameter] public EventCallback<string?> OnSearch { get; set; }
    [Parameter] public EventCallback<int?> OnTabChange { get; set; }

    [Parameter] public PageStateModel? State { get; set; }

    protected override void OnInitialized()
    {
        activeTab = State?.ActiveTab ?? Tabs?.FirstOrDefault()?.Id;
        searchTerm = State?.SearchTerm;
    }

    async void Search(string searchValue)
    {
        cts.Cancel();
        cts = new CancellationTokenSource();

        await Task.Delay(300);

        if (!cts.IsCancellationRequested)
        {
            await OnSearch.InvokeAsync(
                (string.IsNullOrWhiteSpace(searchValue))
                ? null
                : searchValue);

            StateHasChanged();
        }
    }

    async void Tab(int? id)
    {
        activeTab = id;

        var task = OnTabChange.InvokeAsync(id);

        StateHasChanged();

        await task;
    }
}
